package com.zf.gateway.downstream.controller;

import com.zf.common.core.result.RestResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 测试 RestTemplate:
 */
@Slf4j
@RestController
@RequestMapping("/rest-template")
public class RestTemplateTestController {

    /**
     * 来自 {@link com.zf.common.http.rest_template.RestTemplateConfig} 中配置的Bean
     */
    @Resource(name = "restTemplateByUri")
    private RestTemplate restTemplateByUri;

    @Resource(name = "restTemplateByServiceId")
    private RestTemplate restTemplateByServiceId;

    @Resource
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/testServiceId")
    public RestResponse<String> testServiceId() {
        // 通过服务名调用
        // String res = restTemplateByServiceId.getForObject("http://gateway-downstream/test/hello", String.class);
        ResponseEntity<String> res = restTemplateByServiceId.getForEntity("http://gateway-downstream/test/hello", String.class);
        System.out.println(res.getHeaders());
        System.out.println(res.getBody());
        return RestResponse.success(res.getBody());
    }

    @GetMapping("/testUri")
    public RestResponse<String> testUri() {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, "123456");

        // 通过uri调用
        ResponseEntity<String> res = restTemplateByUri.exchange("https://www.baidu.com/", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
        System.out.println(res.getHeaders());
        System.out.println(res.getBody());

        return RestResponse.success(res.getBody());
    }

    @GetMapping("/testLoadBalancerClient")
    public RestResponse<String> testLoadBalancerClient() {
        // 手动选择服务
        ServiceInstance serviceInstance = loadBalancerClient.choose("gateway-downstream");
        // 拼接URL
        String url = String.format("http://%s:%s/test/hello", serviceInstance.getHost(), serviceInstance.getPort());
        String res = restTemplateByUri.getForObject(url, String.class);

        System.out.println(res);
        return RestResponse.success(res);
    }

}
